var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const bodyParser = require("body-parser");
const cros = require("cors");

//引入路由模块
const backRouter = require("./routes/admin/backRouter.js");
const frontRouter = require("@/routes/web/frontRouter.js");

//引入初始化模块
const InitGlobalVariable = require("@/utils/InitGlobalVariable.js");

var app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
//极其坑，只有指定具体目录才可以访问，单独public不行
app.use(express.static(__dirname + "/public/uploaded"));
app.use(express.json());
app.use(
  bodyParser.urlencoded({
    extended: false,
    limit: "1024mb",
  })
);

app.use(cookieParser());
//初始化全局变量
const init = async () => {
  await InitGlobalVariable();
};

(async () => {
  await init();

  backRouterInit();

  // catch 404 and forward to error handler
  app.use(function (req, res, next) {
    next(createError(404));
  });

  // error handler
  app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get("env") === "development" ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.send({
      message: "not found",
    });
  });
})();

function backRouterInit() {
  //引入中间件模块
  //使用跨域中间件
  const corsMiddleware = require("@/routes/middleware/cors.js");
  const jwtMiddleware = require("@/routes/middleware/jwt.js");
  const RBACMiddleware = require("@/routes/middleware/casbin.js");
  // const ListenOnline = require("@/routes/middleware/listen_online.js");
  const OperationLog = require("@/routes/middleware/operationLog.js");

  //设置session存储
  const session = require("express-session");

  //session信息存放在请求体req.session
  app.use(
    session({
      name: "mysession",
      secret: "salt", //密钥
      resave: true, //设置时效期，false的时候如正在用一个软件，但是失效了会突然强制用户重新登录，这种体验不好，true则相反
      saveUninitialized: false, //页面初始化的时候生成一个cookie，但是是无效的
      cookie: {
        maxAge: 1000 * 3600 * 24, // 毫秒与 JWT 过期时间一致
        secure: false, // http模式下设置，这样子才能访问cookie，为true代表https访问cookie
      },
    })
  );
  //使用中间件
  //跨域
  app.use(corsMiddleware());
  //解析token
  app.use(jwtMiddleware());
  //rbac鉴权
  app.use(RBACMiddleware());
  //监听用户在线
  // app.use(ListenOnline());
  app.use(OperationLog());
  //注册后端路由 (统一前缀)
  app.use("/api", backRouter);
}

module.exports = app;
